<template>
  <div class="m-pageView">
    <div class="m-searchPanel">
      <div class="layout-1"><span class="leftLine"></span>查询条件</div>
      <div class="layout-2">
        <el-form :model="searchForm" :inline="true">
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item class="input-with-select">
                <el-input placeholder=" " v-model.trim="searchForm.inputFH" clearable>
                  <el-select v-model="searchForm.typeinputFH" slot="prepend" placeholder="请选择"
                             class="selectInputType">
                    <el-option label="主题" value="theme"></el-option>
                    <el-option label="单号" value="fid"></el-option>
                    <el-option label="名单" value="typeId"></el-option>
                  </el-select>
                </el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11">
              <el-form-item label="" class="select-timepick">
                <el-select placeholder="请选择" v-model="searchForm.typetimeFH">
                  <el-option label="创建时间" value="create"></el-option>
                  <el-option label="分配时间" value="assign"></el-option>
                  <el-option label="预约时间" value="resv"></el-option>
                </el-select>
                <el-date-picker
                  v-model="searchForm.timeFH"
                  type="datetimerange"
                  :unlink-panels="true"
                  :picker-options="pickerOptions"
                  :editable="false"
                  :default-time="['00:00:00','23:59:59']"
                  format="yyyy-MM-dd HH:mm:ss"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="7" class="searchBtns">
              <el-button type="text" @click="showMoreSearchChoise =!showMoreSearchChoise"><span>更多条件</span><i :class="{
              'el-icon-arrow-down':!showMoreSearchChoise,
              'el-icon-arrow-up':showMoreSearchChoise,
              }"></i>
              </el-button>
              <el-button type="primary" icon="el-icon-search" @click="search" :loading="dataListLoading">查询</el-button>
              <el-button type="primary" plain icon="el-icon-refresh" @click="reset">重置</el-button>
            </el-col>
          </el-row>
          <el-collapse-transition>
            <el-row :gutter="30" v-if="showMoreSearchChoise">
              <el-col :span="6">
                <el-form-item label="名单类型">
                  <el-select v-model="searchForm.type" placeholder="请选择" clearable>
                    <el-option label="真实账号" value="1"></el-option>
                    <el-option label="LEAD" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="处理状态">
                  <el-select v-model="searchForm.hstatus" placeholder="请选择" multiple>
                    <el-option label="待处理" value="1"></el-option>
                    <el-option label="处理中" value="2"></el-option>
                    <el-option label="已完成" value="3"></el-option>
                    <el-option label="已取消" value="4"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分配状态">
                  <el-select v-model="searchForm.astatus" placeholder="请选择" clearable>
                    <el-option label="待分配" value="1"></el-option>
                    <el-option label="已分配" value="2"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="标记">
                  <el-select
                    v-model="searchForm.labels"
                    multiple
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteMarkMethod"
                    placeholder="请输入关键词"
                  >
                    <el-option
                      v-for="item in markabels"
                      :label="item.lname"
                      :key="item.lid"
                      :value="item.lid">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="创建人">
                  <el-select
                    v-model="searchForm.createUser"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteUserMethod"
                    placeholder="请输入关键词"
                  >
                    <el-option
                      v-for="item in userList"
                      :label="item._id"
                      :key="item._id"
                      :value="item._id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="分配给">
                  <el-select
                    v-model="searchForm.assigner"
                    clearable
                    filterable
                    remote
                    reserve-keyword
                    :remote-method="remoteUserMethod"
                    placeholder="请输入关键词"
                  >
                    <el-option
                      v-for="item in userList"
                      :label="item._id"
                      :key="item._id"
                      :value="item._id">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-collapse-transition>
        </el-form>
      </div>
    </div>
    <div class="m-dataLayout">
      <div class="m-searchListPanel">
        <div class="layout-1"><span class="leftLine"></span>信息列表</div>
        <el-row class="layout-2">
          <el-col :span="24">
            <el-button type="text" icon="el-icon-plus" @click="showAddFollowUpData=true"
                       v-if="buttonAuthority.follow && buttonAuthority.follow.create">新建
            </el-button>
            <el-button type="text" icon="el-icon-upload" @click="uploadDatas.show=true"
                       v-if="buttonAuthority.follow && buttonAuthority.follow.upload">上传
            </el-button>
            <a :href="downLoadHref" download v-if="buttonAuthority.follow && buttonAuthority.follow.excel">
              <el-button type="text" icon="el-icon-download">导出</el-button>
            </a>
          </el-col>
        </el-row>
      </div>
      <div class="m-dataList">
        <el-table
          :data="dataList"
          style="width: 100%"
          v-loading="dataListLoading"
          element-loading-text="loading..."
          ref="dataList"
          max-height="700"
          @sort-change="tableSortBy"
        >
          <el-table-column
            prop="id"
            width="160"
            label="单号">
            <template slot-scope="scope">
              <a href="javascript:void(0)" @click="fnShwoDetails(scope.row)">{{scope.row.id}}</a>
            </template>
          </el-table-column>
          <el-table-column
            prop="theme"
            label="主题"
            show-overflow-tooltip
            width="120">
          </el-table-column>
          <el-table-column
            prop="type"
            label="名单类型"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.type | typeToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="typeId"
            label="名单"
            width="120">
            <template slot-scope="scope">
              <a href="javascript:void(0)" @click="toInfo(scope.row)">{{scope.row.typeId}}</a>
            </template>
          </el-table-column>
          <el-table-column
            prop="resvTimeStr"
            label="预约时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="resvSndTimeStr"
            label="预约提醒"
            width="160">
          </el-table-column>
          <el-table-column
            prop="hstatus"
            label="处理状态"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.hstatus | hstatusFollowUpToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="astatus"
            label="分配状态"
            width="80">
            <template slot-scope="scope">
              <span>{{scope.row.astatus | astatusToString}}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="assigner"
            label="分配给"
            width="100">
          </el-table-column>
          <el-table-column
            prop="assignTimeStr"
            label="分配时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="createUser"
            label="创建人"
            width="120">
          </el-table-column>
          <el-table-column
            prop="createTimeStr"
            label="创建时间"
            sortable="custom"
            width="160">
          </el-table-column>
          <el-table-column
            prop="labels"
            label="标记"
            width="200">
            <template slot-scope="scope">
              <Comp-tags :label="scope.row.labels"></Comp-tags>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            fixed="right"
            v-if="buttonAuthority.follow && (buttonAuthority.follow.label || buttonAuthority.follow.edit)"
            width="100">
            <template slot-scope="scope">
              <el-dropdown
                :show-timeout="200"
                trigger="click"
                @command="(type)=>{rolDataActive(type,scope.row)}"
              >
                <el-button
                  type="text"
                  icon="el-icon-arrow-down"
                  size="small">
                  更多操作
                </el-button>
                <el-dropdown-menu slot="dropdown">
                  <el-dropdown-item command="edit" v-if="buttonAuthority.follow && buttonAuthority.follow.edit">编辑
                  </el-dropdown-item>
                  <el-dropdown-item command="mark" v-if="buttonAuthority.follow && buttonAuthority.follow.label">标记
                  </el-dropdown-item>
                </el-dropdown-menu>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="m-pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes=pagination.pageSizeList
          :current-page=pagination.pageNo
          :page-size=pagination.pageSize
          layout="total, sizes, prev, pager, next"
          :total=pagination.total>
        </el-pagination>
      </div>
    </div>
    <el-dialog title="上传跟进项" :visible.sync="uploadDatas.show" width="400px" class="m-dialog"
               :close-on-click-modal="false" :close-on-press-escape="false" @close="closeUploadDialog">
      <el-form :model="uploadDatas.form" :rules="uploadDatas.rules" ref="refUploadDatas">
        <el-form-item prop="fileName">
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">上传文件</el-col>
            <el-col :span="13">
              <el-input :disabled="true" v-model="uploadDatas.form.fileName" placeholder="未选择文件"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-upload
                :multiple="false"
                accept=""
                action="/"
                :on-change="handleUpladFileSuccess"
                :show-file-list="false"
                :auto-upload="false">
                <el-button type="text" class="link-btn">文档上传</el-button>
              </el-upload>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">下载模板</el-col>
            <el-col :span="13">
              <el-input value="创建跟进项模板" :disabled="true"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-button type="text" class="link-btn"><a href="/static/xlsTMP/Create-Follow-up.xlsx"
                                                         download>点击下载</a></el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-row class="uploadfilerow">
            <el-col class="title" :span="5">下载模板</el-col>
            <el-col :span="13">
              <el-input value="更新已存在跟进项模板" :disabled="true"></el-input>
            </el-col>
            <el-col :span="6" class="down">
              <el-button type="text" class="link-btn"><a href="/static/xlsTMP/Update-Follow-up.xlsx"
                                                         download>点击下载</a></el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-row class="uploadfilerow">
          <el-form-item label="你希望">
            <el-radio-group v-model="uploadDatas.form.type">
              <el-radio label="1">创建新跟进项</el-radio>
              <el-radio label="2">更新已存在跟进项的资料</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-row>
      </el-form>
      <div class="dialog-tipWords">
        <div class="tipTitle">提示：</div>
        <div class="tipContent">
          1. 不填写的栏位表示不更新<br>
          2. 单次批量上传上限为1000条
        </div>
      </div>
      <div slot="footer">
        <el-button @click="uploadDatas.show = false">取消</el-button>
        <el-button type="primary" @click="uploadDatasSubmit">提交</el-button>
      </div>
    </el-dialog>
    <Comp-Upload-Dialog :show.sync="showUploadDialog" :step.sync="showUploadDialogStep"></Comp-Upload-Dialog>
    <Comp-Add-Follow-Up @addSuccess="queryList" :show.sync="showAddFollowUpData"></Comp-Add-Follow-Up>
    <Comp-Mark @submit="markRowData" :show.sync="showMarkDialog" :markData="{type:'3',labelsStr:activeRow.labels}"></Comp-Mark>
    <Comp-Follow-Up-Details @submit="queryList" :rowDetails="activeRow"
                            :show.sync="showDetails"></Comp-Follow-Up-Details>
  </div>
</template>

<script>
  import {mapGetters} from 'vuex'
  import CompUploadDialog from '@/components/CompUploadDialog.vue'
  import CompAddFollowUp from '@/components/CompAddFollowUp.vue'
  import CompFollowUpDetails from '@/components/CompFollowUpDetails.vue'
  import * as LabelAPI from '@/Api/label'
  import * as FollowUpAPI from '@/Api/followup';
  import * as UserAPI from '@/Api/user';
  import * as Utils from '@/utils'
  import qs from 'qs'
  import ElCol from "element-ui/packages/col/src/col";
  export default {
    name: 'PageFollowUp',
    data () {
      return {
        showAddFollowUpData:false,
        searchForm: {
          typeinputFH: 'typeId',
          inputFH: '',
          typetimeFH: 'create',
          timeFH: Utils.thisWeek(),
          type: '',
          hstatus: [],
          labels: [],
          astatus: '',
          createUser: '',
          assigner: '',
        },
        showDetails: false,
        showUploadDialog:false,//显示上传进度弹窗
        showUploadDialogStep:'ing',//显示上传进度弹窗 -进度
        copySearchForm: null,
        showMarkDialog: false,
        activeRow: {},
        showMoreSearchChoise: false,
        pagination: Utils.commonPagination(),
        pickerOptions: Utils.pickerOptions(),
        dataList: [],
        dataListLoading:false,
        userList: [],
        markabels: [],
        uploadDatas: {
          show: false,
          form: {
            type: '1',
            file: null,
            fileName: ''
          },
          rules: {
            fileName: [
              {required: true, trigger: 'blur', message: '请上传文件'}
            ]
          }
        },
        sortInfo: {},
        ajaxSearchParams:{},
      }
    },
    watch:{
      'searchForm.inputFH'(val){
        if(val) {
          this.searchForm.timeFH = null;
        } else {
          this.searchForm.timeFH = Utils.thisWeek();
        }
      }
    },
    components: {
      ElCol,
      CompUploadDialog,
      CompFollowUpDetails,
      CompAddFollowUp,
    },
    computed: {
      downLoadHref(){
        return FollowUpAPI.followDownload() + '?' + qs.stringify(Object.assign(this.createListParams(), {track: Utils.randomTrack(),token:this.$store.state.app.userInfo.token}), {allowDots: true})
      },
      ...mapGetters([
        'buttonAuthority',
      ]),
    },
    methods: {
      closeUploadDialog(){
        this.uploadDatas.form.file = null;
        this.uploadDatas.form.type = '1';
        this.uploadDatas.form.fileName = '';
      },
      tableSortBy(data) {
        if (!data.order) {
          return;
        }
        this.sortInfo.orderParam = data.prop;
        this.sortInfo.orderType = data.order.substr(0, data.order.length - 6);
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      remoteMarkMethod(queryStr) {
        if (queryStr != '') {
          LabelAPI.labelName({
            type: '3',
            input: queryStr
          })
            .then(res => {
              if (res.code != 0) {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warning'
                })
                return;
              }
              this.markabels = res.data;
            })
            .catch(error => {
              console.log(error);
            })
        }
      },
      markRowData(data){
        FollowUpAPI.followLabel(Object.assign({
          id: this.activeRow.id,
          type: this.activeRow.type,
          typeId: this.activeRow.typeId
        }, data.mark))
          .then(res => {
            if (res.code != 0) {
              this.$notify.warning({
                title: '温馨提示',
                message: res.msg
              })
              return;
            }
            this.queryList();
            this.showMarkDialog = false;
            this.$message({
              message: '标记成功',
              type: 'success'
            });
          })
          .catch(error => {
            console.log(error)
          })

      },
      remoteUserMethod(queryStr) {
        if (queryStr != '') {
          UserAPI.userNickname({
            input: queryStr
          })
            .then(res => {
              if (res.code != '0') {
                this.$notify({
                  title: '温馨提示',
                  message: res.msg,
                  type: 'warn'
                })
                return;
              }
              this.userList = res.data;
            })
            .catch(error => {
              console.log(error)
            })
        }

      },
      rolDataActive(type, row) {
        if (type == 'edit') {
          /*这里有坑，请合并对象之后再赋值*/
          this.activeRow = Object.assign({editType: 'edit'}, row)
          this.showDetails = true;
        }
        if (type == 'mark') {
          this.activeRow = row;
          this.showMarkDialog = true;
        }
      },
      fnShwoDetails(row) {
        this.activeRow = row;
        this.showDetails = true;
      },
      handleSizeChange(size) {
        this.pagination.pageSize = size;
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      handleCurrentChange(index) {
        this.pagination.pageNo = index;
        this.queryList();

      },
      search() {
        this.ajaxSearchParams =  Utils.searchParamsFormat(this.searchForm);
        if (this.pagination.pageNo == 1) {
          this.queryList();
        } else {
          this.pagination.pageNo = 1;
        }
      },
      uploadDatasSubmit() {
        this.$refs.refUploadDatas.validate(flg => {
          if (!flg) {
            return;
          }
          this.showUploadDialog = true;
          this.showUploadDialogStep = 'ing';
          let tabHeader = [];
          if (this.uploadDatas.form.type == '1') {
            tabHeader = ['theme', 'themeDesc', 'type', 'typeId', 'resvTime', 'during', 'assigner']
          } else if (this.uploadDatas.form.type == '2') {
            tabHeader = ['id', 'themeDesc', 'hstatus', 'resvTime', 'during', 'assigner']
          }
          Utils.xlsxToJson(this.uploadDatas.form.file, tabHeader)
            .then(res => {
              if(res.length > 1000) {
                this.showUploadDialog = false;
                this.$alert('上传数据不能超过一千条', '温馨提示', {
                  confirmButtonText: '确定',
                  callback: action => {
                    this.$message({
                      type: 'warning',
                      message: `action: ${ action }`
                    });
                  }
                });
                return;
              }
              this.upLoadDatesService(res)
                .then(res => {
                  this.$notify({
                    title: '温馨提示',
                    message: '数据上传成功',
                    type: 'success'
                  })
                  this.showUploadDialogStep = 'success';
                  if (this.pagination.pageNo == 1) {
                    this.queryList();
                  } else {
                    this.pagination.pageNo = 1;
                  }
                  this.uploadDatas.show = false;
                })
                .catch(error => {
                  if (error) {
                    this.showUploadDialogStep = 'exception';
                  } else {
                    this.showUploadDialog = false;
                  }
                })
            })
            .catch(error => {
              this.showUploadDialog = false;
              this.$message({
                message: error,
                type: 'warning'
              });
            })
        })
      },
      upLoadDatesService(array){
        return new Promise((resolve, reject) => {
          FollowUpAPI.followUpload({
            type: this.uploadDatas.form.type,
            data: JSON.stringify(array)
          })

            .then(res => {
              if (res.code != 0) {
                this.$notify({
                  type: 'warning',
                  title: '温馨提示',
                  message: res.msg,
                })
                reject(true);
                return;
              }
              if (res.data && res.data.length > 0) {
                let _tabHeader = {};
                if (this.uploadDatas.form.type == '1') {
                  _tabHeader = {
                    'theme': '主题必填',
                    'themeDesc': '主题描述\r\n选填',
                    'type': '名单类型\r\n必填',
                    'typeId': '名单   (必填)\r\n填写LEAD手机号码或客户账号',
                    'resvTime': '预约时间  (选填)\r\nYYYY-MM-DD HH:MM',
                    'during': '预约提醒\r\n选填',
                    'assigner': '分配给(选填)\r\n填写用户号码',
                    'remark': '错误描述'
                  };
                } else if (this.uploadDatas.form.type == '2') {
                  _tabHeader = {
                    'id': '单号\r\n必填',
                    'themeDesc': '主题描述\r\n选填',
                    'hstatus': '处理状态\r\n选填',
                    'resvTime': '预约时间  (选填)\r\nYYYY-MM-DD HH:MM',
                    'during': '预约提醒\r\n选填',
                    'assigner': '分配给(选填)\r\n填写用户号码',
                    'remark': '错误描述'
                  };
                }
                Utils.JsonToXlsx(res.data, _tabHeader)
                  .catch(error => {
                    this.$notify({
                      type: 'warning',
                      title: '温馨提示',
                      message: error,
                    })
                  })
              }
              resolve();
            })
            .catch(error => {
              console.log(error)
              reject(false);
            })
        })
      },
      createListParams() {
        return Object.assign(this.ajaxSearchParams, {
          pageNo: this.pagination.pageNo,
          pageSize: this.pagination.pageSize
        }, this.sortInfo)
      },
      queryList(){
        this.dataListLoading = true;
        if (this.$refs.dataList) {
          this.$refs.dataList.bodyWrapper.scrollTop = 0;
        }
        FollowUpAPI.followList(this.createListParams())
          .then(res => {
            this.dataListLoading = false;
            if (res.code != 0) {
              this.$notify({
                title: '温馨提示',
                message: res.msg,
                type: 'warning'
              })
              return;
            }
            this.dataList = res.data.data;
            this.pagination.total = res.data.total;
          })
          .catch(error => {
            this.dataListLoading = false;
            console.log(error)
          })
      },
      reset() {
        this.searchForm = Object.assign({}, this.copySearchForm)
      },
      handleUpladFileSuccess(file){
        this.uploadDatas.form.file = file;
        this.uploadDatas.form.fileName = file.raw.name
      },
      toInfo(row) {
        const loading = this.$loading({
          lock: true,
          text: 'Loading',
          spinner: 'el-icon-loading',
        });
          FollowUpAPI.followBelongInfo({
            type:row.type,
            typeId:row.typeId,
          })
            .then(res=>{
              loading.close();
                if(res.code != '0') {
                  this.$notify({
                    title: '温馨提示',
                    message: res.msg,
                    type: 'warning'
                  })
                  return;
                }
                if(row.type  == '1') {
                    this.$router.push({
                      name:'AccountDetailsInfo',
                      params:{
                          id:res.data.id+'_'+row.typeId+'_'+res.data.phone
                      }
                    })
                } else if(row.type  == '2') {
                  this.$router.push({
                    name:'LeadDetailsLeade',
                    params:{
                      id:res.data.id+'_'+row.typeId
                    }
                  })
                }
            })
            .catch(error=>{
               loading.close();
                console.log(error);
            })
      }
    },
    created(){
      this.copySearchForm = Object.assign({}, this.searchForm);
      this.search();
    }
  }
</script>

<style scoped lang="scss">
</style>

